import { createRouter, createWebHistory } from 'vue-router'
import Layout from './pages/Layout.vue'
import LookStore from './pages/LookStore.vue'
import ManageStore from './pages/ManageStore.vue'
import Lookperson from './pages/Lookperson.vue'
import Manageperson from './pages/Manageperson.vue'
import Login from './pages/Login.vue'
import Register from './pages/Register.vue'
import Welcome from './pages/Welcome.vue'
import QuickRegistration from './pages/QuickRegistration.vue'
import TestTechnicians from './pages/TestTechnicians.vue'
import ServiceStats from './yang/ServiceStats.vue'
import ComponentConfigManager from './yang/components/ComponentConfigManager.vue'
import ChartTest from './yang/components/ChartTest.vue' // 添加图表测试页面
import ScheduleManagement from './Feng/ScheduleManagement.vue' // 添加排班管理页面

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    meta: { requiresAuth: true },
    children: [
      { path: '', name: 'Welcome', component: Welcome },
      { path: '/layout/lookStore', name: 'LookStore', component: LookStore },
      { path: '/layout/manageStore', name: 'ManageStore', component: ManageStore },
      { path: '/layout/lookperson', name: 'Lookperson', component: Lookperson },
      { path: '/layout/manageperson', name: 'Manageperson', component: Manageperson },
      { path: '/layout/serviceStats', name: 'ServiceStats', component: ServiceStats }, // 修改为4-1对应查看服务
      { path: '/quick-registration', name: 'QuickRegistration', component: QuickRegistration },
      { path: '/test-technicians', name: 'TestTechnicians', component: TestTechnicians },
      { path: '/chart-test', name: 'ChartTest', component: ChartTest }, // 添加图表测试路由
      { path: '/schedule-management', name: 'ScheduleManagement', component: ScheduleManagement }, // 添加排班管理路由
    ]
  },
  {
    path: '/component-config',
    name: 'ComponentConfigManager',
    component: ComponentConfigManager
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)

  if (requiresAuth && !token) {
    // 需要登录但没有token，重定向到登录页
    next('/login')
  } else if (token && (to.path === '/login' || to.path === '/register')) {
    // 已登录但访问登录或注册页，重定向到首页
    next('/')
  } else {
    next()
  }
})

export default router
